var api = require("../../api.js"),
  utils = require("../../utils.js"),
  images = require('../../utils/images.js'),
  app = getApp(),
  is_loading = !1,
  is_no_more = !1
var timer = 1;
Page({
  data: {
    swiperHeight: 0,
    childTabbarList: {},
    goodsReleaseList: [],
    goodsUpList: [],
    brandSwipeList: [],
    current_page: 1,
    page_count: 6,
    keyword: "",
    show_type: 0,  // 1代表显示搜索数据, 2代表显示正常列表数据，0代表默认
    tab: 1,
    sort: 1,
    cat_id: 1,    // 商品分类id
    mch_id: 31,  // 商铺id
    banner_list: [],
    curIndex: 0,      // segment index 
    scrollLeft: 0,
    swiperViewHeight: 200,
    showGoodsSortView: false,  // 是否显示分类弹窗
    goodsSortViewTop: 0,
    shopSortList: [],         // 商品分类列表
    shop: {},                 // 店铺相关数据
    searchList: {},            // 商品搜索结果 
    miaosha: null,
    coupon_list: [],
    get_coupon_list: [],
    bargain: [],
    fixSegmentView: false,    // 用于标识商品分类条目视图是否固定在顶部
    segmentViewHeight: 0,     // 商品分类条目视图的高度
    moreIcon: images.nearbyShop.moreIcon,
    moreUpIcon: images.nearbyShop.moreUpIcon,
    navigationIcon: images.nearbyShop.navigationIcon,
    qrCodeIcon: images.nearbyShop.qrCodeIcon,
    switchIcon: images.nearbyShop.switchIcon,
    locationSmallIcon: images.nearbyShop.locationSmallIcon,
    groupIcon: images.index.groupIcon,
    brandbussiness: images.brand.brandbussiness,
    brandEnjoy: images.brand.brandEnjoy,
    brandmiaoleft: images.brand.brandmiaoleft,
    brandmiaoRight01: images.brand.brandmiaoRight01,
    brandmiaoRight02: images.brand.brandmiaoRight02,
    brandmiaoRight03: images.brand.brandmiaoRight03,
    brandmiaoshabottom: images.brand.brandmiaoshabottom,
    brandMore: images.brand.brandMore,
    brandRQ: images.brand.brandRQ,
    brandSearch: images.brand.brandSearch,
  },
  onLoad: function (options) {
    app.pageOnLoad(this)
    if (this.data.mch_id) {
      this.loadBannerData()
      this.loadShopData()
      this.loadNewGoodsReleaseList();
      this.loadNewGoodsUpList();
      this.loadBrandWwipe();
    } else {
      wx.showModal({
        title: "提示",
        content: "店铺id为空，店铺不存在！"
      })
    }
  },
  onShow: function () {
    app.pageOnShow(this);
  },
  onReachBottom: function () {
    if (this.data.show_type == 2) {
      this.getGoodsList();
    }
  },
  onPageScroll(event) {
    // 在页面滚动的过程中，判断商品条目视图是否需要固定在顶部
    const that = this
    let query = wx.createSelectorQuery()
    query.select('.goods-list').boundingClientRect(ref => {
      that.setData({
        fixSegmentView: ref && ref.top <= that.data.segmentViewHeight ? true : false
      })
    }).exec()
  },
  /**
   * 获取店铺信息
   */
  loadShopData: function () {
    const that = this
    const key = "shop_data_mch_id_" + this.data.mch_id
    const cacheData = wx.getStorageSync(key)

    cacheData && this.setData({
      shop: cacheData.shop
    }), wx.showNavigationBarLoading(), this.setData({
      loading: !0
    })

    app.request({
      url: api.mch.shop,
      data: {
        tab: this.data.tab,
        sort: this.data.sort,
        page: 1,
        mch_id: this.data.mch_id,
        cat_id: this.data.cat_id
      },
      success: function (res) {
        1 != res.code ? 0 == res.code && (that.setData({
          shop: res.data.shop,
          mch_id: res.data.shop.id,
          coupon_list: res.data.coupon_list ? res.data.coupon_list : [],
          new_list: res.data.new_list,
          miaosha: res.data.miaosha,
          update_list: res.data.update_list,
          pintuan: res.data.pintuan,
          bargain: res.data.bargain
        }),
          // 动态修改标题为店铺名称
          wx.setNavigationBarTitle({
            // title: res.data.shop.name
            title: '蓝丝羽'
          }),
          // 加载商品分类数据
          that.loadStoreSortData(),
          wx.setStorageSync(key, res.data)) : wx.showModal({
            title: "提示",
            content: res.msg,
            showCancel: !1,
            success: function (showRes) {
              showRes.confirm && wx.redirectTo({
                url: "/mch/shop/shop"
              })
            }
          });
      },
      complete: function () {
        // 开启秒杀
        wx.hideNavigationBarLoading(), that.setData({
          loading: !1
        })
      }
    })
  },
  // 加载搜索数据
  loadData: function () {
    if (this.data.show_type == 2) {
      this.loadShopData();
      return;
    }
    if (this.data.show_type != 1) {
      console.log(this.data.show_type);
      return;
    }
    var that = this
    wx.showLoading({
      title: "加载中"
    }), app.request({
      url: api.mch.search_goods,
      method: "POST",
      data: {
        mch_id: this.data.mch_id,
        keyword: that.data.keyword,
      },
      success: function (d) {
        0 == d.code && that.setData({
          searchList: d.data.banner_list,
        });
      },
      fail: function (d) {
        wx.showToast({
          title: '搜索失败',
          image: "http://runwu100.img.guoxiaoge.cn/icon-warning.png"
        });
      },
      complete: function (d) {
        wx.hideLoading();
      }
    });
  },
  // 轮播图数据
  loadBannerData: function () {
    var that = this;
    app.request({
      url: api.mch.banner,
      data: {
        mch_id: this.data.mch_id,
      },
      success: function (d) {
        0 == d.code && that.setData({
          banner_list: d.data.banner_list[0],
        });
      }
    });
  },
  // 新品发布
  loadNewGoodsReleaseList() {
    var that = this;
    app.request({
      url: api.mch.new_goods_up,
      method: "GET",
      data: {
        // mch_id: this.data.mch_id,
        mch_id: 72,
        keyword: that.data.keyword,
        size: 2,
        page: 1,
        type: 0
      },
      success: function (d) {
        console.log(d.data);
        0 == d.code && that.setData({
          goodsReleaseList: d.data.list || [],
        });
      },
      fail: function (d) {
        wx.showToast({
          title: '搜索失败',
          image: "http://runwu100.img.guoxiaoge.cn/icon-warning.png"
        });
      }
    });
  },
  // 新品上架
  loadNewGoodsUpList() {
    var that = this;
    app.request({
      url: api.mch.new_goods_up,
      method: "GET",
      data: {
        // mch_id: this.data.mch_id,
        mch_id: 72,
        keyword: that.data.keyword,
        size: 2,
        page: 1,
        type: 1
      },
      success: function (d) {
        console.log(d.data);
        0 == d.code && that.setData({
          goodsUpList: d.data.list || [],
        });
      },
      fail: function (d) {
        wx.showToast({
          title: '搜索失败',
          image: "http://runwu100.img.guoxiaoge.cn/icon-warning.png"
        });
      }
    });
  },
  // 中间轮播图
  loadBrandWwipe() {
    var that = this;
    app.request({
      url: api.mch.brand_swipe,
      method: "GET",
      data: {
        // mch_id: this.data.mch_id,
        mch_id: 72,
        keyword: that.data.keyword,
      },
      success: function (d) {
        console.log(d.data);
        0 == d.code && that.setData({
          brandSwipeList: d.data.list || [],
        });
      },
      fail: function (d) {
        wx.showToast({
          title: '搜索失败',
          image: "http://runwu100.img.guoxiaoge.cn/icon-warning.png"
        });
      }
    });
  },
  imageLoad(e) {
    const imgWidth = e.detail.width;
    const imgHeight = e.detail.height;
    const ratio = imgWidth / imgHeight;
    this.setData({
      swiperHeight: wx.getSystemInfoSync().windowWidth / ratio
    })
    console.log(this.data.swiperHeight);
  },
  /**
   * 加载商铺分类数据 
   */
  loadStoreSortData() {
    var that = this;
    var path = "shop_cat_list_mch_id_" + this.data.shop.id,
      cacheData = wx.getStorageSync(path);
    const mchId = this.data.shop.id
    cacheData && that.setData({
      shopSortList: cacheData
    }), wx.showNavigationBarLoading(), app.request({
      url: api.mch.shop_cat,
      data: {
        mch_id: mchId
      },
      success: function (res) {
        0 == res.code && (that.setData({
          shopSortList: res.data.list,
          cat_id: res.data.list.length > 0 ? res.data.list[0].id : 0,
          current_page: 0,
          page_count: 0,
          tab: 2,
          sort: 0,
          no_more: false,
          goods_list: []
        }),
          // 计算分类视图的高度
          that.computedSegmentViewHeight(),
          // 加载第一个分类的数据
          that.getGoodsList(), wx.setStorageSync(path, res.data.list))
      },
      complete: function () {
        wx.hideNavigationBarLoading()
      }
    })
  },
  getGoodsList: function () {
    if (this.data.shopSortList.length === 0) {
      return
    }
    var a = this;
    // waring
    // const mch_id = 24
    // const cat_id = 68
    const cat_id = this.data.cat_id
    const mch_id = this.data.shop.id
    if (3 != a.data.tab && !a.data.loading && !a.data.no_more) {
      a.setData({
        loading: !0
      });
      const page = (a.data.current_page || 0) + 1;
      console.log('page: ' + page)
      app.request({
        url: api.mch.shop,
        data: {
          mch_id: mch_id,
          tab: a.data.tab,
          sort: a.data.sort,
          page: page,
          cat_id: cat_id,
        },
        success: function (t) {
          0 == t.code && (1 == a.data.tab && (t.data.goods_list && t.data.goods_list.length ? (a.data.hot_list = a.data.hot_list.concat(t.data.goods_list), a.setData({
            hot_list: a.data.hot_list,
            current_page: page
          })) : a.setData({
            no_more: !0
          })),
            2 == a.data.tab && (t.data.goods_list && t.data.goods_list.length ? (a.data.goods_list = a.data.goods_list.concat(t.data.goods_list), a.setData({
              goods_list: a.data.goods_list,
              current_page: page,
              show_type: 2
            })) : a.setData({
              no_more: !0
            })))
        },
        complete: function () {
          console.log('goods_list')
          console.log(a.data.goods_list)
          a.setData({
            loading: !1
          })
        }
      })
    }
  },
  /**
   * 商品加载更多
   */
  loadMoreGoodsData() {

  },

  onClickItem() {
    wx.navigateTo({
      url: '/pages/entry-info-lanyu/entry-info?type=1',
    })
  },

  inputFocus: function (t) {
    this.setData({
      show: !0
    });
  },
  inputBlur: function (t) {
    this.setData({
      show: !1
    });
  },
  inputConfirm: function (t) {
    this.onClickSearch();
  },
  inputChange: function (t) {
    this.setData({
      keyword: t.detail.value
    });
  },
  onClickSearch: function (t) {
    if (this.data.keyword) {
      this.setData({
        show_type: 1
      });
    } else {
      this.setData({
        show_type: 2
      });
    }
    this.loadData();
  },
  // 点击更多按钮，显示分类窗口
  onClickMoreButton() {
    this.setData({
      showGoodsSortView: true
    })
  },
  // 隐藏分类窗口
  onClickSortItem(event) {
    const index = parseInt(event.target.dataset.index);
    if (index !== this.data.curIndex) {
      this.switchSegmentIndex(index)
    }
    this.setData({
      showGoodsSortView: false
    })
  },
  // 隐藏分类窗口
  onClickMaskView() {
    this.setData({
      showGoodsSortView: false
    })
  },
  // 修改商品导航index
  onSwitchSegment(event) {
    const index = parseInt(event.target.dataset.index);
    if (index !== this.data.curIndex) {
      this.switchSegmentIndex(index)
    }
  },
  // 切换商品类别
  switchSegmentIndex(index) {
    this.setData({
      curIndex: index,
      cat_id: this.data.shopSortList[index].id,
      current_page: 0,
      tab: 2,
      sort: 0,
      no_more: false,
      goods_list: []
    })
    this.getGoodsList()
    // 调整item的位置，显示当前选中的item
    const that = this
    if (index > 2) {
      var query = wx.createSelectorQuery()
      query.select('.scroll-segment-view').boundingClientRect(function (res) {
        if (res) {
          that.setData({
            scrollLeft: (index - 2) * 75
          })
        }
      })
      query.exec()
    } else {
      this.setData({
        scrollLeft: 0
      })
    }
  },
  /**
   * 打开地图
   */
  goMapPage() {
    var that = this;
    wx.getSetting({
      success: function (res) {
        res.authSetting["scope.userLocation"] ? that.openLocationPage() : app.getauth({
          content: "需要获取您的地理位置授权，请到小程序设置中打开授权！",
          cancel: !1,
          success: function (authRes) {
            authRes.authSetting["scope.userLocation"] && that.openLocationPage()
          }
        });
      }
    });
  },
  goMapQRPage() {
    wx.navigateTo({
      url: `/mch/shop-qrcode/shop-qrcode?mch_id=${this.data.mch_id}`
    })
  },
  /**
   * 打开地图
   */
  openLocationPage() {
    const that = this
    wx.openLocation({
      latitude: parseFloat(that.data.shop.lat),
      longitude: parseFloat(that.data.shop.log),
      name: that.data.shop.name,
      address: that.data.shop.address
    });
  },
  /**
   * 在获取分类数据后，计算segment view的高度
   */
  computedSegmentViewHeight() {
    const that = this
    let query = wx.createSelectorQuery()
    query.select('.segment-view').boundingClientRect(ref => {
      that.setData({
        segmentViewHeight: ref && ref.height
      })
    }).exec()
  }
});